package com.itheima.reggie.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//创建拦截器
@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //得到session
        Employee employee =(Employee)request.getSession().getAttribute(Constant.SESSION_EMPLOYEE);
        //判断employee是否为空
        if (employee!=null){
            //将对象存入ThreadLocal
            EmployeeHolder.set(employee);
            return true;
        }else {
            log.info("用户未被激活");
        }
        //将错误信息向前端返回
        ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
        String json = new ObjectMapper().writeValueAsString(resultInfo);
        response.getWriter().write(json);
        return false;

    }

    //请求离开服务器 关闭ThreadLocal对象
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeHolder.remove();
    }
}
